<template>
  <el-container class="CategoryAdminList">
    <el-header class="mt20 flex">
      <span class="title fs18 mr10">分类列表</span>
      <Cbutton size="small" icon="el-icon-plus" @click.native="openDialog('one')">添加分类</Cbutton>
      <el-divider />
    </el-header>
    <el-main v-loading="loading">
      <el-row class="GoodSku-title" style="padding: 15px 0px 15px 20px;text-align: center;font-size: 16px;">
        <el-col :span="5">创建时间</el-col>
        <el-col :span="5">类别名称</el-col>
        <el-col :span="5">类型描述</el-col>
        <el-col :span="9">操作</el-col>
      </el-row>
      <el-collapse v-model="activeNames" class="CategoryAdminList-collapse">
        <el-collapse-item v-for="(item, index) in tableData" :key="index" :name="index">
          <!-- 一级分类 -->
          <el-row slot="title" :gutter="20" class="flex" style="width: 100%;height: 100%;text-align: center;font-size: 15px;">
            <el-col :span="5">{{ item.createTime | setTime }}</el-col>
            <el-col :span="5">
              <span v-if="!item.edit">{{ item.name | isNullData }}</span>
              <div v-else @click.stop><el-input v-model="item.name" type="text" class="inputTextCenter" placeholder="请输入类别名称" size="medium" clearable /></div>
            </el-col>
            <el-col :span="5">
              <span v-if="!item.edit">{{ item.type | isNullData }}</span>
              <div v-else @click.stop><el-input v-model="item.type" type="text" class="inputTextCenter" placeholder="请输入类型" size="medium" clearable /></div>
            </el-col>
            <el-col :span="9">
              <el-button v-if="!item.edit" size="small" icon="el-icon-edit" type="primary" @click.stop="item.edit = true">编辑</el-button>
              <el-button v-if="item.edit" size="small" icon="el-icon-close" type="danger" @click.stop="handlerEdit(item, 'cancel')">取消</el-button>
              <el-button v-if="item.edit" size="small" icon="el-icon-check" type="success" @click.stop="handlerEdit(item, 'determine', 'one')">确定</el-button>
              <el-button size="small" icon="el-icon-plus" type="info" @click.stop="openDialog('two', item)">添加子类</el-button>
              <el-popconfirm
                title="确定要执行该操作吗？"
                @confirm="removeCategory(item.id, 'one', index)"
              >
                <el-button slot="reference" size="small" icon="el-icon-delete" type="danger" class="ml10" @click.stop>删除</el-button>
              </el-popconfirm>
            </el-col>
          </el-row>
          <!-- 二级分类 -->
          <el-row v-for="(it, i) in item.children" :key="it.id" :gutter="20" class="flex mb10" style="width: 100%;height: 100%;text-align: center;font-size: 15px;">
            <el-col :span="5">{{ it.createTime | setTime }}</el-col>
            <el-col :span="5">
              <el-row class="flex">
                <el-col :span="12" class="flex" style="justify-content: end;">
                  <Cimage v-if="!it.edit" :src="it.icon" fit="cover" round width="50px" height="50px" />
                  <CuploadImageOnce v-else :external-image-url.sync="it.icon" width="50px" height="50px" />
                </el-col>
                <el-col :span="12" class="flex" style="justify-content: start;">
                  <span v-if="!it.edit" class="ml10">{{ it.name | isNullData }}</span>
                  <div v-else class="ml10" @click.stop><el-input v-model="it.name" type="text" class="inputTextCenter" placeholder="请输入类别名称" size="medium" clearable /></div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="5">
              <span v-if="!it.edit">{{ it.type | isNullData }}</span>
              <div v-else @click.stop><el-input v-model="it.type" type="text" class="inputTextCenter" placeholder="请输入类型" size="medium" clearable /></div>
            </el-col>
            <el-col :span="9">
              <el-button v-if="!it.edit" size="small" icon="el-icon-edit" type="primary" @click.stop="it.edit = true">编辑</el-button>
              <el-button v-if="it.edit" size="small" icon="el-icon-close" type="danger" @click.stop="handlerEdit(it, 'cancel')">取消</el-button>
              <el-button v-if="it.edit" size="small" icon="el-icon-check" type="success" @click.stop="handlerEdit(it, 'determine', 'two')">确定</el-button>
              <el-popconfirm
                title="确定要执行该操作吗？"
                @confirm="removeCategory(it.id, 'two', index, i)"
              >
                <el-button slot="reference" size="small" icon="el-icon-delete" type="danger" class="ml10" @click.stop>删除</el-button>
              </el-popconfirm>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-main>
    <Cdialog
      :visible="dialog.visible"
      :title="dialog.title"
      width="600px"
      class="CategoryAdminList-dialog"
      @handleClose="handleClose"
    >
      <el-form :model="dialog" label-width="100px" label-position="left" class="CategoryAdminList-dialog-form">
        <el-form-item label="类型名称：">
          <el-input v-model="dialog.name" type="text" placeholder="请输入类型名称" size="medium" clearable />
        </el-form-item>
        <el-form-item label="类型描述：">
          <el-input v-model="dialog.type" type="text" placeholder="请输入类型描述" size="medium" clearable />
        </el-form-item>
        <el-form-item v-if="dialog.className === 'two'" label="图片预览：">
          <CuploadImageOnce :external-image-url.sync="dialog.icon" width="100px" height="100px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="flexCenter">
        <el-button size="small" type="primary" @click="submit">提 交</el-button>
        <el-button size="small" @click="handleClose">取 消</el-button>
      </div>
    </Cdialog>
  </el-container>
</template>
<script>
import {
  categoryGetOne,
  categoryGetTwo,
  categoryModify,
  categoryDelete
} from '@/api/category'
import CuploadImageOnce from '@/components/CuploadImageOnce'
export default {
  name: 'CategoryAdminList',
  components: { CuploadImageOnce },
  data() {
    return {
      loading: true,
      activeNames: '', // 当前激活的面板(如果是手风琴模式，绑定值类型需要为string，否则为array)
      tableData: [], // 总数据
      dialog: { // 弹窗数据
        visible: false,
        title: '',
        className: '', // 传one || two （一级或二级）
        id: '',
        parentId: '',
        name: '', // 名称
        icon: '',
        type: '' // 类型描述
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 弹窗提交
    async submit() {
      if (!this.dialog.name) {
        this.$message.error('请输入类型名称')
        return
      }
      if (!this.dialog.type) {
        this.$message.error('请输入类型描述')
        return
      }
      if (this.dialog.className === 'two' && !this.dialog.icon) {
        this.$message.error('请上传预览图')
        return
      }
      const res = await categoryModify({
        id: this.dialog.id ? this.dialog.id : undefined,
        parentId: this.dialog.parentId ? this.dialog.parentId : undefined,
        className: this.dialog.className,
        name: this.dialog.name,
        icon: this.dialog.icon ? this.dialog.icon : undefined,
        type: this.dialog.type
      })
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getList()
        this.handleClose()
      }
    },
    // 打开弹窗
    openDialog(className, item) {
      switch (className) {
        case 'one':
          this.dialog.title = '添加分类'
          break
        case 'two':
          this.dialog.title = '添加子类'
          this.dialog.parentId = item.id
          break
      }
      this.dialog.visible = true
      this.dialog.className = className
    },
    // 关闭弹窗
    handleClose() {
      this.dialog = { // 弹窗数据
        visible: false,
        title: ''
      }
    },
    // 编辑操作
    handlerEdit(item, type, className) {
      switch (type) {
        case 'cancel':
          item.edit = false
          item.name = item.oldName
          item.type = item.oldType
          if (item.oldIcon) item.icon = item.oldIcon
          break
        case 'determine':
          item.className = className
          this.categoryModify(item)
          break
      }
    },
    // 修改或新增分类接口
    categoryModify(item) {
      return new Promise(resolve => {
        categoryModify(item).then(res => {
          if (res.code === 0) {
            this.$message.success(res.msg)
            // 本地修改数据（重置）
            item['edit'] = false
            item['oldName'] = item.name
            item['oldType'] = item.type
            resolve()
          }
        })
      })
    },
    // 删除一级或二级分类
    async removeCategory(id, className, indexParent, index) {
      const res = await categoryDelete({
        id: id,
        className: className
      })
      if (res.code === 0) {
        this.$message.success(res.msg)
        // 删除本地数据
        if (className === 'one') {
          this.tableData.splice(indexParent, 1)
        } else {
          this.tableData[indexParent].children.splice(index, 1)
        }
        this.$forceUpdate()
      }
    },
    // 初始化
    async getList() {
      const res = await categoryGetOne()
      if (res.code === 0) {
        const { data: oneData } = res
        const two_res = await categoryGetTwo()
        if (two_res.code === 0) {
          const { data: twoData } = two_res
          oneData.forEach(item => { // 匹配数据
            item.id = item.id.toString()
            item['children'] = []
            item['edit'] = false
            item['oldName'] = item.name
            item['oldType'] = item.type
            twoData.forEach(it => {
              // eslint-disable-next-line eqeqeq
              if (item.id == it.parentId) {
                it['edit'] = false
                it['oldName'] = it.name
                it['oldType'] = it.type
                it.id = it.id.toString()
                const url = it.icon[0].url
                it.icon = url
                it['oldIcon'] = url
                item['children'].push(it)
              }
            })
          })
          this.tableData = oneData
          this.loading = false
          console.log(this.tableData, '数据')
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/element-variables.scss";
.CategoryAdminList{
  &-title{
    background-color: rgba($color: $--color-primary, $alpha: .09);
  }
  &-collapse{
    border-top: 0;
    border-bottom: 0;
    ::v-deep .el-collapse-item{
      margin: 20px 0;
    }
    ::v-deep .el-collapse-item__header{
      flex-direction: row-reverse;
      &:hover{
        // background-color: rgba(0, 0, 0, 0.05);
      }
      .el-collapse-item__arrow{
        margin-left: 15px;
        font-size: 16px;
        font-weight: bold;
      }
    }
    ::v-deep .el-collapse-item__content{
      &:hover{
        // background-color: rgba(0, 0, 0, 0.05);
      }
    }
    ::v-deep .el-collapse-item__wrap{
      border-bottom: 0;
    }
    ::v-deep .el-collapse-item__header{
      height: inherit;
      line-height: inherit;
      padding: 15px 0;
      border-bottom: 0;
      background-color: rgba($color: $--color-primary, $alpha: .09);
    }
    ::v-deep .el-collapse-item__content{
      background-color: rgba($color: $--color-primary, $alpha: .05);
      padding: 15px 0 15px 40px;
    }
  }
}
.CategoryAdminList-dialog{
  &-form{
    width: 100%;
    height: 100%;
    padding: 20px 10px 0 10px;
  }
}
</style>
